import cv2
import numpy as np

img = cv2.imread("./img/opencv-logo.png")
h, w, _ = img.shape
img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

mask = np.zeros((h, w), dtype=np.uint8)
for i in range(h):
    for j in range(w):
        h_val = img_hsv[i, j][0]
        s_val = img_hsv[i, j][1]
        v_val = img_hsv[i, j][2]
        # 判断红色
        if (156 <= h_val <= 180 or 0 <= h_val <= 10) and 43 <= s_val <= 255 and 46 <= v_val <= 255:
            mask[i, j] = 255

red = cv2.bitwise_and(img[:, :, 2], mask)

# 轮廓检测
contours, _ = cv2.findContours(red, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

# 轮廓的标注
for contour in contours:
    # boundingRect 从轮廓点中取出最大范围的矩形区域
    x, y, w1, h1 = cv2.boundingRect(contour)
    cv2.rectangle(img, (x, y), (x + w1, y + h1), color=(0, 0, 0), thickness=2)
    cv2.putText(img, "red", (x, y), 0, 2, color=(0, 0, 0), thickness=2)

# 修改对应区域的图形的颜色(将红色区域改变为绿色)
for i in range(h):
    for j in range(w):
        if mask[i, j] == 255:
            img_hsv[i, j][0] = 77

# --------注意:hsv的图像最终要转化为bgr的图才能正常显示
img_bgr = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR)
cv2.imshow("img", img_bgr)
cv2.waitKey(0)
